import axios from "axios";
import ElementUI from "element-ui";
import router from "./router";

// 统一前缀
axios.defaults.baseURL = "http://localhost:8081"

/**
 *  创建请求对象
 */
const request = axios.create({
    timeout: 5000,
    headers: {
       'content-Type' : 'application/json; charset:utf-8'
    }
})
/**
 * 请求拦截
 */
request.interceptors.request.use(config => {   
   // 请求头带上token   return config}
  const token = localStorage.getItem("token");
  
  config.headers['Authorization'] = token ? token : ''
  return config
})
/* request.interceptors.request.use(config => {
    let token = localStorage.getItem['token']

    if(!token) {
      token = ''
    }
    config.headers['authorization'] = token
    return config
}) */
/**
 * 响应拦截
 */
request.interceptors.response.use(response => {
    debugger
    let res = response.data;
    if(res.code === 200) {
        return response;
    } else {
      ElementUI.Message({
        message: res.msg? res.msg : '系统异常！',
        type: 'error'
    });
        return Promise.reject(response.data.msg)
    }
},error => {
    debugger
    if(error.response.data && error.response.data.msg) {
        error.msg = error.response.data.msg
        ElementUI.Message({
            message: error.msg,
            type: 'error'
        });
        return Promise.reject(error)
    }
    if(error.response.status == 401) {
        // 删除令牌信息
        localStorage.setItem("token",null);
        router.push("/login")
    }

    ElementUI.Message({
      message: error.message,
      type: 'error'
    });
    return Promise.reject(error)
})

export default request